package com.shwread.android.ui.page;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.GlideUtil;
import com.NewActionHelp;
import com.google.gson.reflect.TypeToken;
import com.hzdracom.epubreader.activity.ReadingEpubActivity;
import com.hzdracom.epubreader.consts.EpubConst;
import com.shwread.android.qysw.activity.BookShelfActivity;
import com.shwread.android.qysw.activity.BookTicketActivity;
import com.shwread.android.qysw.activity.MainActivity;
import com.shwread.android.qysw.activity.ReadingBookActivity;
import com.shwread.android.qysw.activity.ReadingmagazineActivity;
import com.shwread.android.qysw10000227.R;
import com.shwread.android.ui.dialog.DeleteShelfBookDialog;
import com.shwread.android.ui.dialog.DeleteShelfCoverDialog;
import com.shwread.android.ui.dialog.NoNetDialog;
import com.shwread.http.base.EmptyHttpResponseHandler;
import com.shwread.http.base.Log;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.http.base.TextHttpResponseHandler;
import com.shwread.http.util.JSONUtil;
import com.shwread.http.util.Logger;
import com.shwread.httpsdk.http.callback.ActionListener;
import com.shwread.httpsdk.http.callback.BaseAction;
import com.shwread.httpsdk.http.callback.IoTaskProgress;
import com.shwread.httpsdk.http.download.DownloadForProgressAction;
import com.shwread.httpsdk.http.face.QryMsgsByPositionAction;
import com.shwread.httpsdk.http.face.QryUseServiceFinishedAction;
import com.shwread.httpsdk.util.NetUtil;
import com.tgx.tina.android.ipc.framework.IUIPage;
import com.ui.dialog.CustomDialog;

import org.apache.http.Header;
import org.geometerplus.android.util.QyreaderPerferencesUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xml.sax.SAXException;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import base.tina.core.task.infc.ITaskProgress.TaskProgressType;
import base.tina.core.task.infc.ITaskResult;
import logic.bean.BookBean;
import logic.bean.ChapterInfo;
import logic.bean.MessageBean;
import logic.bean.MessageInfo;
import logic.bean.NewBookBean;
import logic.bean.TOCItem;
import logic.beanenum.BookStatus_Enum;
import logic.beanenum.BookType_Enum;
import logic.beanenum.MessagePosition_enum;
import logic.constants.Const;
import logic.constants.DefaultConsts;
import logic.dao.BookDao;
import logic.util.FileUtil;
import logic.util.NetworkUtil;
import logic.util.SDcardUtil;
import logic.util.Util;
import logic.util.Utils;
import logic.util.qryChapterInfoUtil;
import logic.xml.parser.NCXHandler;


/**
 * 书架页面page
 */
public class BookShelfPage extends AbstractUIPage<MainActivity> implements OnClickListener/* , ShelfListener */ {

    private static BookShelfPage instance;
    private List<BookBean> books;
    /**
     * 推荐书籍列表
     */
    private List<BookBean> recommendbooks;
    private TextView tvTitle;
    private Button btnBack;
    private ImageView ivPersion;
    private GridView gridView;
    private RelativeLayout messageLayout, serviceLayout;
    private ImageView close, ivServiceClose;
    private GridAdapter gridAdapter;
    private TextView tvMsgTitle, tvServiceContent;
    private TextView tvMsgContent;
    private MessageInfo msgInfo;
    private boolean serviceFlag;

    private BookDao bookMarkDao;

    private ExplorerPage pageExplorer;
    private List<TOCItem> catalogList;
    private QyreaderPerferencesUtil qyUtil;

    public BookShelfPage(MainActivity t) {
        super(t);
    }

    public static BookShelfPage getInstance(MainActivity t) {
        if (instance == null) {
            instance = new BookShelfPage(t);
        } else {
            instance.setActivity(t);
        }
        return instance;
    }

    @Override
    public <E extends Activity> View createView(E arg0, int arg1) {
        if (null != curMyView) {
            return curMyView;
        }
        curMyView = bActivity.getLayoutInflater().inflate(R.layout.bookshelf_lay, null);
        initData();
        initView();
        setListener();
        qyUtil = QyreaderPerferencesUtil.getInstance(bActivity, Const.phone_number);
        return curMyView;
    }

    private void initData() {
        books = new ArrayList<>();
        recommendbooks = new ArrayList<>();
        gridAdapter = new GridAdapter();
        bookMarkDao = BookDao.getInstance(bActivity);
    }

    void initView() {
        tvTitle = (TextView) curMyView.findViewById(R.id.common_header_name);
        tvTitle.setText("个人书架");
//		tvTitle.setText(bActivity.getResources().getString(R.string.maintab_bookshelf));
        ivPersion = (ImageView) curMyView.findViewById(R.id.common_header_persion);
        ivPersion.setVisibility(View.VISIBLE);
        btnBack = (Button) curMyView.findViewById(R.id.common_header_back);
        btnBack.setVisibility(View.GONE);
        gridView = (GridView) curMyView.findViewById(R.id.bookshelf_grid);
        messageLayout = (RelativeLayout) curMyView.findViewById(R.id.bookshelf_tip_message);
        serviceLayout = (RelativeLayout) curMyView.findViewById(R.id.service_overdue_layout);
        close = (ImageView) curMyView.findViewById(R.id.bookshelf_tip_close);
        ivServiceClose = (ImageView) curMyView.findViewById(R.id.service_overdue_view_cancel);
        tvMsgTitle = (TextView) curMyView.findViewById(R.id.bookshelf_tip_title);
        tvMsgContent = (TextView) curMyView.findViewById(R.id.bookshelf_tip_text);
        tvServiceContent = (TextView) curMyView.findViewById(R.id.service_overdue_view_content);

        serviceLayout.setVisibility(View.GONE);

//        if (BoutiquePage.fromBoutique) {
            btnBack.setVisibility(View.VISIBLE);
            ivPersion.setVisibility(View.GONE);
//        }
    }

    void setListener() {
        ivPersion.setOnClickListener(this);
        close.setOnClickListener(this);
        btnBack.setOnClickListener(this);
        ivServiceClose.setOnClickListener(this);
        tvServiceContent.setOnClickListener(this);

        gridView.setAdapter(gridAdapter);
        gridView.setOnItemClickListener(new GridClick());
        gridView.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                if (arg2 >= recommendbooks.size() && arg2 < arg0.getAdapter().getCount() - 1) {
                    DeleteShelfBookDialog shelfDeleteDialog = new DeleteShelfBookDialog(bActivity, (BookBean) arg0.getAdapter().getItem(arg2));
                    shelfDeleteDialog.show();
                }
                return true;
            }
        });
        messageLayout.setOnClickListener(this);
    }

    private boolean existFile(BookBean bean) {
        if (bean.syncStatus == BookBean.SYNC && bean.startTime <= 0 && bean.endTime <= 0) {
            return false;
        }
        String path = "";
        final String suffix = bean.book_type == BookBean.BOOK_TYPE_EPUB3 ? EpubConst.EPUB_SUFFIX : ".ceb";
        if (bean.status == BookStatus_Enum.LOCAL.getValue()) {
            path = bean.path;
        } else if (bean.status == BookStatus_Enum.ONLINE.getValue()) {
            path = FileUtil.OnlinePath(String.valueOf(bean.book_id)) + FileUtil.Book_CATALOGUE;
        } else if (bean.status == BookStatus_Enum.DOWNLOAD.getValue()) {
            path = FileUtil.DownloadPath() + String.valueOf(bean.book_id) + suffix;
//			path = FileUtil.DownloadPath() + String.valueOf(bean.book_id) + ".ceb";
        }

        if (Util.isNotEmpty(path) && FileUtil.exists(path)) {
            return true;
        } else {
            if (bean.syncStatus == BookBean.NO_SYNC) {
                //弹出清理封面窗口
                new DeleteShelfCoverDialog(bActivity, bean, books).show();
            }
        }
        return false;
    }

    void readLocalBook(BookBean bean) {
        Intent intent = new Intent(bActivity, ReadingBookActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(ReadingBookActivity.BOOKSTATUS, bean.status);
        intent.putExtra(DefaultConsts.book_contentId_s, "-1");
        intent.putExtra(DefaultConsts.book_name, bean.book_name);
        String urlpath = bean.path;
        Uri url = Uri.parse(urlpath);
        intent.setData(url);
        bActivity.startActivity(intent);
    }

    void readMagazineBook(BookBean bean) {
        //		int index = 0;
        //		if(bean.syncStatus==BookBean.SYNC && bean.startTime<=0 && bean.endTime<=0){ //同步的最新数据
        //			if (null != catalogList && catalogList.size() > 0){
        //				for (int i = 0; i < catalogList.size(); i++)
        //                {
        //	                if(catalogList.get(i).getId().equals(String.valueOf(bean.server_chapterid))){
        //	                	index = i;
        //	                	QyreaderPerferencesUtil.getInstance(bActivity, Const.phone_number).setChapterIndex(String.valueOf(bean.book_id), index);
        //	                	break;
        //	                }
        //                }
        //			}
        //		}else{
        //			index = QyreaderPerferencesUtil.getInstance(bActivity, Const.phone_number).getChapterIndex(String.valueOf(bean.book_id));
        //		}
        int index = QyreaderPerferencesUtil.getInstance(bActivity, Const.phone_number).getChapterIndex(String.valueOf(bean.book_id));
        Intent intent = new Intent(bActivity, ReadingmagazineActivity.class);
        //		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra(DefaultConsts.chapterId_index_i, index);
        intent.putExtra("BookMarkBean", bean);
        bActivity.startActivity(intent);
    }

    void readTextBook(final BookBean bean) {
//        final int index = 0;
//        if (bean.syncStatus == BookBean.SYNC && bean.startTime <= 0 && bean.endTime <= 0) { //同步的最新数据
//            if (null != catalogList && catalogList.size() > 0) {
//                for (int i = 0; i < catalogList.size(); i++) {
//                    if (catalogList.get(i).getId().equals(String.valueOf(bean.server_chapterid))) {
//                        index = i;
//                        QyreaderPerferencesUtil.getInstance(bActivity, Const.phone_number).setChapterIndex(String.valueOf(bean.book_id), index);
//                        break;
//                    }
//                }
//            }
//        } else {
//            index = QyreaderPerferencesUtil.getInstance(bActivity, Const.phone_number).getChapterIndex(String.valueOf(bean.book_id));
//        }
//        Intent intent = new Intent(bActivity, ReadingBookActivity.class);
//        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
//        intent.putExtra(ReadingBookActivity.BOOKSTATUS, bean.status);
//        intent.putExtra(DefaultConsts.book_contentId_s, String.valueOf(bean.book_id));
//        intent.putExtra(DefaultConsts.chapterId_index_i, index);
//        intent.putExtra(DefaultConsts.book_name, bean.book_name);
//        intent.putExtra("IsFromCatalogActivity", true);
//        String urlpath = FileUtil.OnlinePath(String.valueOf(bean.book_id)) + FileUtil.Book_CATALOGUE;
//        Uri url = Uri.parse(urlpath);
//        intent.setData(url);
//        bActivity.startActivity(intent);
        NewActionHelp.qryReadBookByBookId(context, bean.book_id, new ObjectHttpResponseHandler<NewBookBean>() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                Log.e("1111112", s);
                int index = QyreaderPerferencesUtil.getInstance(bActivity, Const.phone_number).getChapterIndex(String.valueOf(bean.book_id));
                toReadingBook(index);
            }

            @Override
            public void onSuccess(int i, Header[] headers, NewBookBean bookBean, String s) {
                Log.e("111111", bookBean.getChapterIndex() + "ss");
                toReadingBook(bookBean.getChapterIndex());
            }

            /**
             * 跳转到阅读界面
             *
             * @param index 阅读章节进度
             */
            private void toReadingBook(int index) {
                Intent intent = new Intent(bActivity, ReadingBookActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra(ReadingBookActivity.BOOKSTATUS, bean.status);
                intent.putExtra(DefaultConsts.book_contentId_s, String.valueOf(bean.book_id));
                intent.putExtra(DefaultConsts.chapterId_index_i, index);
                intent.putExtra(DefaultConsts.book_name, bean.book_name);
                intent.putExtra("IsFromCatalogActivity", true);
                String urlpath = FileUtil.OnlinePath(String.valueOf(bean.book_id)) + FileUtil.Book_CATALOGUE;
                Uri url = Uri.parse(urlpath);
                intent.setData(url);
                bActivity.startActivity(intent);
            }

            @Override
            public Type getType() {
                return new TypeToken<NewBookBean>() {
                }.getType();
            }
        });
    }

    void readDownloadBook(BookBean bean) {
        if (bean.book_type == BookBean.BOOK_TYPE_EPUB3) {
            Intent intent = new Intent(context, ReadingEpubActivity.class);
            intent.putExtra("BookID", bean.book_id);
            intent.setData(Uri.parse(bean.path));
            bActivity.startActivity(intent);
            return;
        }

        int index = QyreaderPerferencesUtil.getInstance(bActivity, Const.phone_number).getLocalIndex(String.valueOf(bean.book_id));
        Intent intent = new Intent(bActivity, ReadingBookActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(ReadingBookActivity.BOOKSTATUS, bean.status);
        intent.putExtra(DefaultConsts.book_contentId_s, String.valueOf(bean.book_id));
        intent.putExtra(DefaultConsts.chapterId_index_i, index);
        intent.putExtra(DefaultConsts.book_name, bean.book_name);
        String urlpath = FileUtil.DownloadPath() + String.valueOf(bean.book_id) + ".ceb";
        Uri url = Uri.parse(urlpath);
        intent.setData(url);
        bActivity.startActivity(intent);
    }

    private void loadImageUrl(ImageView iv, int position, String url) {
        if (iv != null && Util.isNotEmpty(url) && iv.getTag() != null && Integer.valueOf(iv.getTag().toString()) == position) {
            GlideUtil.load(context,url, iv);
        }
    }

    @Override
    public int enter(IUIPage<?> arg0) {
        getData();
        if (NetworkUtil.isNetAvailable(bActivity)) {
            //查询书架消息
            new QryMsgsByPositionAction(bActivity, MessagePosition_enum.BOOKSHELF.getValue(),
                    "", 1, 1, new MsgListener()).start();
            NewActionHelp.qryRecommendBookList(bActivity, 1, 50, new TextHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, final String responseString) {
                    new Thread() {
                        @Override
                        public void run() {
                            saveBooks(responseString);
                        }
                    }.start();
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                    Logger.e(responseString, throwable);
                }
            });
        }
        return 0;
    }

    private void getData() {
        books = bookMarkDao.getShelfBooks(Const.phone_number);
        recommendbooks = bookMarkDao.getReferralBooks(Const.phone_number);

        //		System.out.println("书架 - 阅读历史：" + this.books.toString());
        //		System.out.println("书架 - 推荐书籍：" + recommendbooks.toString());

        gridAdapter.notifyDataSetChanged();

        if (NetUtil.isNetworkConnected(context)) {
            if (serviceFlag || System.currentTimeMillis() - QyreaderPerferencesUtil.getInstance(bActivity, Const.phone_number).getQryUseServiceFinishedActionTime() > 60 * 60 * 24 * 1000) {
                if (!BoutiquePage.fromBoutique)
                    new QryUseServiceFinishedAction(bActivity, new MyUseServiceFinishedAction()).start();
            }
        }
    }

    @Override
    public int leave(IUIPage<?> arg0) {
        return 0;
    }

    @Override
    public void notifyView(int arg0, Bundle arg1) {
        switch (arg0) {
            case DefaultConsts.UPDATEUI_SYNCBOOKS_FINISH:
            case DefaultConsts.UPDATEUI_BOOKSHELF_BOOKS_OK:
            case DefaultConsts.DELETE_BOOKSHELF_BOOKS_OK:
            case DefaultConsts.PAGE_ONRESUME_CODE:
                getData();
                break;
        }
    }

    @Override
    public void setStatus(int arg0) {

    }

    @Override
    public View updateView(int arg0, ITaskResult arg1) {
        return null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.common_header_back:
                if (BookShelfActivity.OFFINE_READ){//离线看书
                    ((BookShelfActivity)bActivity).toLoginActivity();
                } else {
                    bActivity.onBackPressed();
                }
                break;
            case R.id.common_header_persion:
                if (NetworkUtil.isNetAvailable(bActivity)) {
                    bActivity.goPersonalActivity();
                } else {
                    new NoNetDialog(bActivity).show();
                }
                break;
            case R.id.bookshelf_tip_close:
                //TODO 待添加消息关闭的业务逻辑
                messageLayout.setVisibility(View.GONE);
                readMessage();
                break;
            case R.id.bookshelf_tip_message:
                readMessage();
                toMessageDetail(msgInfo);
                break;
            case R.id.service_overdue_view_cancel:
                serviceLayout.setVisibility(View.GONE);
                break;
            case R.id.service_overdue_view_content:
                serviceFlag = true;
                Intent intent = new Intent(bActivity, BookTicketActivity.class);
                intent.putExtra(DefaultConsts.from_page, DefaultConsts.TAG_BOOKSHELF);
                bActivity.startActivity(intent);
                break;
        }
    }

    private void readMessage() {
        if (null == msgInfo) return;
        if (msgInfo.getIsRead().toLowerCase().equals("n")) {
            //			new ReadMsgBySendIdAction(bActivity, String.valueOf(msgInfo.getMsgViewId()), new EmptyAction()).start();
            NewActionHelp.readMsgBySendId(bActivity, String.valueOf(msgInfo.getMsgViewId()), new EmptyHttpResponseHandler());
        }
        qyUtil.addMsgId(msgInfo.getMsgId());
    }

    void toMessageDetail(MessageInfo info) {
        if (Util.isNotEmpty(info.getAddressUrl())) {
            bActivity.goWebViewActivity(info);
        } else {
            switch (info.getMsgType()) {
                case MessageInfo.TYPE_BOOK:
                    bActivity.goBookDetailActivity(info.getBooks());
                    break;
                case MessageInfo.TYPE_SYSTEM:
                    bActivity.goSystemNotiActivity(info);
                    break;
                case MessageInfo.TYPE_LIVES:
                    bActivity.goWebViewActivity(info);
                    break;
            }
        }
    }

    void downloadChapterInfo(BookBean bean) {
        //		new QryChapterInfoAction(bActivity, String.valueOf(bean.book_id), catalogList.get(0).getId(), new ChapterInfoListener(bean)).start();
        new qryChapterInfoUtil().qryChapterInfo(bActivity, String.valueOf(bean.book_id), catalogList.get(0).getId(), new ChapterInfoHandler(bean));
    }

    private void initDirctory(final BookBean bean) {
        String dirctory = FileUtil.OnlinePath(String.valueOf(bean.book_id)) + FileUtil.Book_CATALOGUE;
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser;
        try {
            parser = factory.newSAXParser();
            InputStream is = new FileInputStream(new File(dirctory));
            NCXHandler handle = new NCXHandler();
            parser.parse(is, handle);
            is.close();
            if (null != catalogList && catalogList.size() > 0) {
                catalogList.removeAll(catalogList);
            }
            catalogList = handle.getNavPointList();
            bean.path = dirctory;
            NewActionHelp.qryChapterInfo(context, String.valueOf(bean.book_id), catalogList.get(0).getId(), new ObjectHttpResponseHandler<ChapterInfo>() {

                @Override
                public Type getType() {
                    return new TypeToken<ChapterInfo>() {
                    }.getType();
                }

                @Override
                public void onFailure(int statusCode, Header[] arg1, String responseString, Throwable arg3) {
                    if (statusCode == 6201 || statusCode == 6202) {
                        try {
                            Utils.showToast(context, JSONUtil.getString(responseString));
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        return;
                    }
                }

                @Override
                public void onSuccess(int statusCode, Header[] arg1, ChapterInfo arg2, String responseString) {
                    updateData(bean);
                    if (BookType_Enum.BOOK.getValue().equals(String.valueOf(bean.book_type))) {
                        readTextBook(bean);
                    } else if (BookType_Enum.MAGAZINE.getValue().equals(String.valueOf(bean.book_type))) {
                        readMagazineBook(bean);
                    }
                }

            });
        } catch (IOException | SAXException | ParserConfigurationException e) {
            e.printStackTrace();
        }
    }

    //	private class MessageRefresh extends BaseAction{
    //		@Override
    //		public void OK(Object obj) {
    //			bActivity.getUIHandler().sendEmptyMessage(DefaultConsts.MESSAGE_REFRESH_CODE);
    //		}
    //	}

    void downloadDirecoty(final BookBean bean) {
        final boolean isReferral = bean.status == BookStatus_Enum.REFERRAL.getValue();
        String ncxPath;
        final String savePath = FileUtil.OnlinePath(String.valueOf(bean.book_id)) + FileUtil.Book_CATALOGUE;
        ncxPath = bean.ncxUrl;
        if (isReferral) {
            bean.status = BookStatus_Enum.ONLINE.getValue();
        } else {
            try {
                FileUtil.deleteFolderFile(FileUtil.OnlinePath(String.valueOf(bean.book_id)), false);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (FileUtil.exists(savePath)) {
            bean.path = savePath;
            if (!(catalogList != null && catalogList.get(0) != null && catalogList.get(0).getId() != null)) {
                if (Util.isNotEmpty(ncxPath)) {
                    new DownloadForProgressAction(bActivity, ncxPath, savePath, new DirecotryProgress(bean)).start();
                } else {
                    Util.showToast(bActivity, "目录下载地址为空 ");
                }
                return;
            }
            NewActionHelp.qryChapterInfo(context, String.valueOf(bean.book_id), catalogList.get(0).getId(), new ObjectHttpResponseHandler<ChapterInfo>() {

                @Override
                public Type getType() {
                    return new TypeToken<ChapterInfo>() {
                    }.getType();
                }

                @Override
                public void onFailure(int statusCode, Header[] arg1, String responseString, Throwable arg3) {
                    if (statusCode == 6201 || statusCode == 6202) {
                        try {
                            Utils.showToast(context, JSONUtil.getString(responseString));
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        return;
                    }
                }

                @Override
                public void onSuccess(int statusCode, Header[] arg1, ChapterInfo arg2, String responseString) {
                    if (isReferral) updateData(bean);
                    if (BookType_Enum.BOOK.getValue().equals(String.valueOf(bean.book_type))) {
                        readTextBook(bean);
                    } else if (BookType_Enum.MAGAZINE.getValue().equals(String.valueOf(bean.book_type))) {
                        readMagazineBook(bean);
                    }
                }

            });
        } else {
            if (Util.isNotEmpty(ncxPath)) {
                new DownloadForProgressAction(bActivity, ncxPath, savePath, new DirecotryProgress(bean)).start();
            } else {
                Util.showToast(bActivity, "目录下载地址为空");
            }
        }
    }

    void updateData(BookBean bean) {
        if (bean.status == BookStatus_Enum.REFERRAL.getValue()) {
            bean.logo_url = bean.logo_url.split(";")[0];
        }
        bean.create_time = String.valueOf(System.currentTimeMillis());
        bookMarkDao.addBooktoShelf(bean);
    }

    //	@Override
    //	public void getShelfBook(List<BookMarkBean> books, List<BookMarkBean> referBooks) {
    //		System.out.println("getShelfBook - 阅读历史：" + books.toString());
    //		System.out.println("getShelfBook - 推荐书籍：" + referBooks.toString());
    //		if (this.books.size() > 0) this.books.removeAll(books);
    //		this.books = books;
    //		if (recommendbooks.size() > 0) recommendbooks.removeAll(referBooks);
    //		recommendbooks = referBooks;
    //
    //		System.out.println("书架 - 阅读历史：" + this.books.toString());
    //		System.out.println("书架 - 推荐书籍：" + recommendbooks.toString());
    //	}

    private void saveBooks(String json) {
        if (Util.isEmpty(json)) return;
        try {
            JSONObject obj = new JSONObject(json);
            JSONArray arr = obj.getJSONObject("returnObject").getJSONArray("book");
            if (null != arr && arr.length() > 0) {
                List<BookBean> data = new ArrayList<BookBean>();
                bookMarkDao.delReferralBooks(Const.phone_number);
                for (int i = 0; i < arr.length(); i++) {
                    obj = arr.getJSONObject(i);
                    final long bookId = obj.getLong("bookId");
                    if (null == bookMarkDao.getBookById(bookId, Const.phone_number)) {
                        data.add(new BookBean(BookStatus_Enum.REFERRAL.getValue(), obj.getLong("bookId"), obj.getString("name"), Integer.valueOf(BookType_Enum.BOOK.getValue()), Const.phone_number, obj.getString("logoUrl"), obj.getString("ncxUrl")));
                    }
                }
                arr = null;
                obj = null;
                //	        	bookMarkDao.delReferralBooks(Const.phone_number);
                bookMarkDao.addReferralBooks(data);
                bActivity.getUIHandler().sendEmptyMessage(DefaultConsts.UPDATEUI_BOOKSHELF_BOOKS_OK);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private class GridClick implements OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (!SDcardUtil.isSDCARDMounted()) {
                Util.showToast(bActivity, bActivity.getResources().getString(R.string.image_save_sdcard_deny));
                return;
            }
            if (position == parent.getAdapter().getCount() - 1) {
                pageExplorer = new ExplorerPage(MainActivity.instance);
                pageExplorer.setBookInfo(books);
                MainActivity.instance.changePage(pageExplorer, IUIPage.DEFAULT_STATUS);
            } else {
                final BookBean bean = (BookBean) parent.getAdapter().getItem(position);
                if (position < recommendbooks.size()) {
                    if (NetworkUtil.isNetAvailable(bActivity)) {
                        //推荐书籍阅读
                        //Util.showToast(bActivity, "打开推荐书籍");
                        if (BookShelfActivity.OFFINE_READ) {//离线阅读状态下
                            CustomDialog.Builder builder = new CustomDialog.Builder(bActivity);
                            builder.setMessage("您当前为离线阅读状态，请在线登录后进行阅读");
                            builder.setPositiveButton("去登录", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    ((BookShelfActivity)bActivity).toLoginActivity();
                                    dialog.dismiss();
                                }
                            });
                            builder.setNegativeButton("再等等",new android.content.DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            });
                            builder.create().show();
                            return;
                        }
                        downloadDirecoty(bean);
                    } else {
                        new NoNetDialog(bActivity).show();
                    }
                } else {
                    if (bean.status == BookStatus_Enum.LOCAL.getValue()) {
                        if (existFile(bean)) {
                            readLocalBook(bean);
                        }
                    } else if (bean.status == BookStatus_Enum.ONLINE.getValue()) {//在线书籍阅读
                        if (NetworkUtil.isNetAvailable(bActivity)) {
                            if (BookShelfActivity.OFFINE_READ) {//离线阅读状态下
                                CustomDialog.Builder builder = new CustomDialog.Builder(bActivity);
                                builder.setMessage("您当前为离线阅读状态，请在线登录后进行阅读");
                                builder.setPositiveButton("去登录", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        ((BookShelfActivity)bActivity).toLoginActivity();
                                        dialog.dismiss();
                                    }
                                });
                                builder.setNegativeButton("再等等",new android.content.DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                });
                                builder.create().show();
                                return;
                            }
                            if (BookType_Enum.BOOK.getValue().equals(String.valueOf(bean.book_type)) || BookType_Enum.TEXT.getValue().equals(String.valueOf(bean.book_type))) {
                                if (existFile(bean)) {
                                    NewActionHelp.qryChapterInfo(context, String.valueOf(bean.book_id), String.valueOf(bean.chapter_id), new ObjectHttpResponseHandler<ChapterInfo>() {

                                        @Override
                                        public Type getType() {
                                            return new TypeToken<ChapterInfo>() {
                                            }.getType();
                                        }

                                        @Override
                                        public void onFailure(int statusCode, Header[] arg1, String responseString, Throwable arg3) {
                                            if (statusCode == 6201 || statusCode == 6202) {
                                                try {
                                                    Utils.showToast(context, JSONUtil.getString(responseString));
                                                } catch (JSONException e) {
                                                    // TODO Auto-generated catch block
                                                    e.printStackTrace();
                                                }
                                                return;
                                            }
                                        }

                                        @Override
                                        public void onSuccess(int statusCode, Header[] arg1, ChapterInfo arg2, String responseString) {
                                            readTextBook(bean);
                                        }
                                    });
                                } else if (bean.syncStatus == BookBean.SYNC) {
                                    //TODO 下载目录，根据server_chapterid找到chapterid,最后去阅读
                                    downloadDirecoty(bean);
                                }
                            } else if (BookType_Enum.MAGAZINE.getValue().equals(String.valueOf(bean.book_type))) {
                                if (existFile(bean)) {
                                    NewActionHelp.qryChapterInfo(context, String.valueOf(bean.book_id), String.valueOf(bean.chapter_id), new ObjectHttpResponseHandler<ChapterInfo>() {

                                        @Override
                                        public Type getType() {
                                            return new TypeToken<ChapterInfo>() {
                                            }.getType();
                                        }

                                        @Override
                                        public void onFailure(int statusCode, Header[] arg1, String responseString, Throwable arg3) {
                                            if (statusCode == 6201 || statusCode == 6202) {
                                                try {
                                                    Utils.showToast(context, JSONUtil.getString(responseString));
                                                } catch (JSONException e) {
                                                    // TODO Auto-generated catch block
                                                    e.printStackTrace();
                                                }
                                                return;
                                            }
                                        }

                                        @Override
                                        public void onSuccess(int statusCode, Header[] arg1, ChapterInfo arg2, String responseString) {
                                            readMagazineBook(bean);
                                        }
                                    });
                                } else if (bean.syncStatus == BookBean.SYNC) {
                                    //TODO 下载目录，根据server_chapterid找到chapterid,最后去阅读
                                    downloadDirecoty(bean);
                                }
                            } else if (BookType_Enum.UMD.getValue().equals(String.valueOf(bean.book_type))) {
                                //TODO 漫画阅读
                            } else if (BookType_Enum.LISTEN.getValue().equals(String.valueOf(bean.book_type))) {
                                //TODO 有声阅读
                            }
                        } else {
                            new NoNetDialog(bActivity).show();
                        }
                    } else if (bean.status == BookStatus_Enum.DOWNLOAD.getValue()) {
//                        if (existFile(bean)) {
//                            readDownloadBook(bean);
//                        }
                        //TODO 需求:下载阅读的书籍不进行同步到服务器,导致阅读起始终止时间为0     因此单独处理这块逻辑
                        String suffix = bean.book_type == BookBean.BOOK_TYPE_EPUB3 ? EpubConst.EPUB_SUFFIX : ".ceb";
                        String path =  FileUtil.DownloadPath() + String.valueOf(bean.book_id) + suffix;
                        if (Util.isNotEmpty(path) && FileUtil.exists(path)) {
                            readDownloadBook(bean);
                        } else {
                            if (bean.syncStatus == BookBean.NO_SYNC) {
                                //弹出清理封面窗口
                                new DeleteShelfCoverDialog(bActivity, bean, books).show();
                            }
                        }
                    } else {
                    }
                }
            }
        }
    }

    private class GridAdapter extends BaseAdapter {
        ViewHolder holder;

        @Override
        public int getCount() {
            if (books == null) {
                return 0;
            }
            return books.size() + recommendbooks.size() + 1;
        }

        @Override
        public Object getItem(int position) {
            if (position < recommendbooks.size()) { //推荐书籍
                return recommendbooks.get(position);
            } else if (position < getCount() - 1) {
                return books.get(position - recommendbooks.size());
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View view, ViewGroup parent) {
            BookBean bean = null;
            boolean isAdd;
            if (view == null) {
                holder = new ViewHolder();
                view = bActivity.getLayoutInflater().inflate(R.layout.bookshelf_grid_item, null);
                holder.body = (RelativeLayout) view.findViewById(R.id.bookshelf_grid_item_layout);
                holder.add = (RelativeLayout) view.findViewById(R.id.bookshelf_grid_item_add_layout);
                holder.cover = (ImageView) view.findViewById(R.id.bookshelf_grid_item_cover);
                holder.icon = (ImageView) view.findViewById(R.id.bookshelf_grid_item_type_img);
                holder.recommend = (TextView) view.findViewById(R.id.bookshelf_grid_item_recommend);
                holder.recentRead = (TextView) view.findViewById(R.id.bookshelf_grid_item_recent_read);
                holder.name = (TextView) view.findViewById(R.id.bookshelf_grid_item_name);
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }
            holder.cover.setTag(position);
            isAdd = (position == getCount() - 1);
            holder.add.setVisibility(isAdd ? View.VISIBLE : View.GONE);
            holder.body.setVisibility(isAdd ? View.GONE : View.VISIBLE);
            if (!isAdd && holder != null) {
                holder.recommend.setVisibility(position < recommendbooks.size() ? View.VISIBLE : View.GONE);
                holder.recentRead.setVisibility((position >= recommendbooks.size() && position < recommendbooks.size() + 2) ? View.VISIBLE : View.GONE);
                if (position < recommendbooks.size()) { //推荐书籍
                    if (recommendbooks.size() > 0) {
                        bean = recommendbooks.get(position);
                        GlideUtil.load(context, bean.logo_url, R.drawable.bookcover_default, holder.cover);
                        setBookShlefTypeIcon(holder.icon, bean.status, String.valueOf(bean.book_type));
                    }
                } else if (position < getCount() - 1) {
                    bean = (BookBean) getItem(position);
                    GlideUtil.load(context, bean.logo_url, R.drawable.bookcover_default, holder.cover);
                }
                if (bean != null) {
                    setBookShlefTypeIcon(holder.icon, bean.status, String.valueOf(bean.book_type));
                    holder.name.setText(bean.book_name);
                }
            }
            return view;
        }
    }

    class ViewHolder {
        RelativeLayout body, add;
        ImageView icon;
        ImageView cover;
        TextView recommend, recentRead, name;
    }

    private class MyUseServiceFinishedAction extends BaseAction {
        @Override
        public void OK(final Object obj) {

            if (obj != null && !Util.isEmpty(obj.toString())) {
                bActivity.getUIHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        QyreaderPerferencesUtil.getInstance(bActivity, Const.phone_number).setQryUseServiceFinishedActionTime(System.currentTimeMillis());
                        tvServiceContent.setText(Html.fromHtml(obj.toString() + "<u>立即续订</u>"));
                        serviceLayout.setVisibility(View.VISIBLE);
                    }
                });
            } else {
                serviceLayout.setVisibility(View.GONE);
                serviceFlag = false;
            }
        }
    }

    private class ChapterInfoHandler extends TextHttpResponseHandler {

        private BookBean bean;

        public ChapterInfoHandler(BookBean bean) {
            super();
            this.bean = bean;
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            //			Message msg = Message.obtain();
            //			msg.what = GET_CHAPTERINFO_ERROR;
            //			Bundle bundle = new Bundle();
            //			bundle.putInt("result", resultCode);
            //			bundle.putString("message", message);
            //			msg.setData(bundle);
            //			handler.sendMessage(msg);
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, String responseString) {
            readTextBook(bean);
            updateData(bean);
        }

    }

    class ChapterInfoListener implements ActionListener {
        private BookBean bean;

        public ChapterInfoListener(BookBean bean) {
            super();
            this.bean = bean;
        }

        @Override
        public void OK(Object obj) {
            bActivity.getUIHandler().post(new Runnable() {
                @Override
                public void run() {
                    readTextBook(bean);
                    updateData(bean);
                }
            });
        }

        @Override
        public void ERROR(int resultCode, String message) {
            //			Message msg = Message.obtain();
            //			msg.what = GET_CHAPTERINFO_ERROR;
            //			Bundle bundle = new Bundle();
            //			bundle.putInt("result", resultCode);
            //			bundle.putString("message", message);
            //			msg.setData(bundle);
            //			handler.sendMessage(msg);
        }

        @Override
        public void HTTPERROR(int statusCode) {

        }

    }

    class DirecotryProgress implements IoTaskProgress {
        private BookBean bean;

        public DirecotryProgress(BookBean bean) {
            super();
            this.bean = bean;
        }

        @Override
        public void createProgress(HttpType httpType, TaskProgressType type, long max) {
        }

        @Override
        public void updateProgress(HttpType httpType, TaskProgressType type, long increase, long max) {
        }

        @Override
        public void finishProgress(HttpType httpType, TaskProgressType type) {
            bActivity.getUIHandler().post(new Runnable() {
                @Override
                public void run() {
                    initDirctory(bean);
                    //					downloadChapterInfo(bean);
                }
            });
        }
    }

    class MsgListener implements ActionListener {
        @Override
        public void OK(Object obj) {
            MessageBean msgBean = ((MessageBean) obj);
            //TODO  此处业务逻辑待完善
            if (null != msgBean.getColumns() && msgBean.getColumns().size() > 0) {
                msgInfo = msgBean.getColumns().get(0);
                if (!qyUtil.checkMsgId(msgInfo.getMsgId())) {
                    bActivity.getUIHandler().post(new Runnable() {
                        @Override
                        public void run() {
                            messageLayout.setVisibility(View.VISIBLE);
                            tvMsgTitle.setText(msgInfo.getTitle());
                            tvMsgContent.setText(msgInfo.getShortMsg());
                        }
                    });
                }
            } else {
                bActivity.getUIHandler().post(new Runnable() {

                    @Override
                    public void run() {
                        messageLayout.setVisibility(View.GONE);
                    }
                });
            }
        }

        @Override
        public void ERROR(int resultCode, String message) {
            bActivity.getUIHandler().post(new Runnable() {

                @Override
                public void run() {
                    messageLayout.setVisibility(View.GONE);
                }
            });
        }

        @Override
        public void HTTPERROR(int statusCode) {

        }
    }
}
